package com.kern.service;

import com.alibaba.fastjson.JSON;
import com.kern.pojo.Content;
import com.kern.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by caoshi at 15:24 2021-07-25
 */
@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public boolean parseContent(String keyWords) throws IOException {
        // 1. 解析数据
        List<Content> contentList = HtmlParseUtil.getDataFromHtml(keyWords);

        // 2. 将解析好的数据放入es
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        for (Content cont : contentList) {
            bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(cont), XContentType.JSON));
        }

        BulkResponse resp = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !resp.hasFailures();
    }


    /**
     * 分页查询
     * @param keyWords
     * @param pageNum
     * @param pageSize
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> searchByPage(String keyWords, int pageNum, int pageSize) throws IOException {
        List<Map<String, Object>> result = new ArrayList<>();

        if (pageNum <= 1) pageNum = 1;

        SearchRequest searchRequest = new SearchRequest("jd_goods");

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyWords);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 设置分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        // 执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResp = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析搜索结果
        SearchHit[] hits = searchResp.getHits().getHits();

        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            result.add(sourceAsMap);
        }

        return result;
    }



    public List<Map<String, Object>> searchByPageHighlight(String keyword, int pageNum, int pageSize) throws IOException {
        List<Map<String, Object>> result = new ArrayList<>();

        if (pageNum <= 1) pageNum = 1;

        SearchRequest searchRequest = new SearchRequest("jd_goods");

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        // 精准匹配
        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(queryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 关键字高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style=\"color:red; background-color: yellow\">");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);


        // 执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResp = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = searchResp.getHits().getHits();

        // 解析并封装结果
        for (SearchHit hit : hits) {

            // 原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            // 获取高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            if (title != null) {

                Text[] fragments = title.getFragments();
                StringBuilder str = new StringBuilder();
                for (Text text : fragments) {
                    str.append(text);
                }
                sourceAsMap.put("title", str.toString());
            }

            result.add(sourceAsMap);
        }

        return result;

    }




}
